package com.example.shuqishixi;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import java.util.List;

@WebServlet(name = "uploadServlet", value = "/uploadServlet")
public class UploadServlet extends HttpServlet {

    private static final String UPLOAD_DIR = "uploads";
    private static final String DB_URL = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "123456";
    private static final String PYTHON_SCRIPT_PATH = "D:\\shuqishixi\\daima\\t\\22082120\\22082120\\代码\\video_analysis.py";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        try {
            HttpSession session = request.getSession(false);
            if (session == null) {
                writeError(out, "未检测到登录信息，请重新登录");
                return;
            }

            Object usernameObj = session.getAttribute("username");
            if (usernameObj == null || !(usernameObj instanceof String)) {
                writeError(out, "未检测到有效用户，请重新登录");
                return;
            }

            String username = (String) usernameObj;

            String uploadPath = getServletContext().getRealPath("/") + File.separator + UPLOAD_DIR;
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            List<FileItem> items;
            try {
                items = upload.parseRequest(request);
            } catch (Exception e) {
                writeError(out, "解析上传请求失败");
                return;
            }

            String action = null;
            FileItem videoItem = null;

            for (FileItem item : items) {
                if (item.isFormField()) {
                    if ("action".equals(item.getFieldName())) {
                        action = item.getString();
                    }
                } else {
                    videoItem = item;
                }
            }

            if (videoItem == null) {
                writeError(out, "未接收到文件数据");
                return;
            }

            if (action == null || (!"upload".equals(action) && !"analyze".equals(action))) {
                writeError(out, "无效或缺失的 action 参数");
                return;
            }

            String originalFileName = new File(videoItem.getName()).getName();
            String fileExtension = "";
            int dotIndex = originalFileName.lastIndexOf(".");
            if (dotIndex > 0) {
                fileExtension = originalFileName.substring(dotIndex);
            }

            String uniqueFileName = System.currentTimeMillis() + "_" +
                    (int)(Math.random() * 10000) + fileExtension;
            String filePath = uploadPath + File.separator + uniqueFileName;

            File storeFile = new File(filePath);
            videoItem.write(storeFile);

            if ("analyze".equals(action)) {
                System.out.println("准备调用Python脚本分析视频...");
                System.out.println("Python脚本路径: " + PYTHON_SCRIPT_PATH);
                System.out.println("视频文件路径: " + filePath);

                int[] result = runPythonScript(filePath);

                System.out.println("Python脚本返回结果: ");
                System.out.println("建筑损坏: " + result[0]);
                System.out.println("人员受伤: " + result[1]);
                System.out.println("树木损坏: " + result[2]);

                saveAnalysisResult(username, uniqueFileName, result[0], result[1], result[2]);

                out.write(String.format(
                        "{\"success\": true, \"message\": \"分析完成\", " +
                                "\"filename\": \"%s\", " +
                                "\"damaged_building\": %d, " +
                                "\"damaged_person\": %d, " +
                                "\"damaged_tree\": %d}",
                        uniqueFileName, result[0], result[1], result[2]
                ));
            } else if ("upload".equals(action)) {
                out.write(String.format(
                        "{\"success\": true, \"message\": \"上传完成\", " +
                                "\"filename\": \"%s\"}",
                        uniqueFileName
                ));
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            writeError(out, "上传失败：" + ex.getMessage());
        } finally {
            out.close();
        }
    }

    private void writeError(PrintWriter out, String message) {
        out.write(String.format("{\"success\": false, \"error\": \"%s\"}", message));
    }

    private int[] runPythonScript(String videoPath) {
        int[] result = {0, 0, 0};
        try {
            ProcessBuilder pb = new ProcessBuilder("python", PYTHON_SCRIPT_PATH, videoPath);
            pb.redirectErrorStream(true);
            Process process = pb.start();

            System.out.println("Python进程已启动，等待输出...");

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), "GBK")
            );

            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("Python脚本输出: " + line);
                if (line.startsWith("building=")) {
                    result[0] = Integer.parseInt(line.split("=")[1]);
                } else if (line.startsWith("person=")) {
                    result[1] = Integer.parseInt(line.split("=")[1]);
                } else if (line.startsWith("tree=")) {
                    result[2] = Integer.parseInt(line.split("=")[1]);
                }
            }

            int exitCode = process.waitFor();
            System.out.println("Python脚本执行完成，退出码: " + exitCode);

        } catch (Exception e) {
            System.err.println("调用Python脚本时出错: " + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    private void saveAnalysisResult(String username, String videoName, int building, int person, int tree) {
        String sql = "INSERT INTO video_analysis (username, video_name, damaged_building, damaged_person, damaged_tree) VALUES (?, ?, ?, ?, ?)";
        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             PreparedStatement ps = conn.prepareStatement(sql)) {

            ps.setString(1, username);
            ps.setString(2, videoName);
            ps.setInt(3, building);
            ps.setInt(4, person);
            ps.setInt(5, tree);
            ps.executeUpdate();


            System.out.println("准备保存分析结果: " +
                    "username=" + username +
                    ", video=" + videoName +
                    ", building=" + building +
                    ", person=" + person +
                    ", tree=" + tree);

// 保存前检查数据库连接
            try (Connection testConn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
                System.out.println("数据库连接测试成功");
            }


            System.out.println("分析结果已保存到数据库");

        } catch (SQLException e) {
            System.err.println("保存分析结果到数据库时出错: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
